package org.easy.core.context;

import com.alibaba.ttl.TransmittableThreadLocal;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 获取当前线程变量中的 用户id、用户名称、Token等信息,请求来源FROM_SOURCE
 * 注意： 必须在网关通过请求头的方法传入，同时在HeaderInterceptor拦截器设置值。 否则这里无法获取
 *
 * @author link
 */
public class SecurityContextHolder {
    private static final TransmittableThreadLocal<Map<String, Object>> THREAD_LOCAL = new TransmittableThreadLocal<>();

    public static void set(String key, Object value) {
        if (value == null) {
            return;
        }
        Map<String, Object> map = getLocalMap();
        map.put(key, value);
    }

    public static <T> T get(String key) {
        Map<String, Object> map = getLocalMap();
        return cast(map.getOrDefault(key, null));
    }

    public static <T> T get(String key, Class<T> clazz) {
        Map<String, Object> map = getLocalMap();
        return cast(map.getOrDefault(key, null));
    }

    public static <T> T cast(Object obj) {
        return (T) obj;
    }

    public static Map<String, Object> getLocalMap() {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (map == null) {
            map = new ConcurrentHashMap<>();
            THREAD_LOCAL.set(map);
        }
        return map;
    }

    public static void setLocalMap(Map<String, Object> threadLocalMap) {
        THREAD_LOCAL.set(threadLocalMap);
    }

    public static Long getUserId() {
        return get(SecurityConstants.JWT_USERID);
    }

    public static void setUserId(Long userId) {
        set(SecurityConstants.JWT_USERID, userId);
    }


    public static void setToken(String userKey) {
        set(SecurityConstants.TOKEN, userKey);
    }


    public static String getToken() {
        return get(SecurityConstants.TOKEN);
    }

    public static void setClient(String userKey) {
        set(SecurityConstants.CLIENT, userKey);
    }


    public static String getClient() {
        return get(SecurityConstants.CLIENT);
    }

    public static void setLocation(String location) {
        set(SecurityConstants.LOCATION, location);
    }

    public static String getLocation() {
        return get(SecurityConstants.LOCATION);
    }


    public static void setLoginUserKey(String userKey) {
        set(SecurityConstants.LOGIN_USER_KEY, userKey);
    }


    public static String getLoginUserKey() {
        return get(SecurityConstants.LOGIN_USER_KEY);
    }


    public static void remove() {
        THREAD_LOCAL.remove();
    }


}
